package com.lhl.fw.core.data.converter;

import com.lhl.fw.core.base.BaseDbEnum;
import com.lhl.fw.core.utils.ClassUtils;
import io.swagger.annotations.Api;

import javax.annotation.Nullable;
import javax.persistence.AttributeConverter;
import java.util.stream.Stream;

/**
 * @className: com.lhl.fw.core.data.converter.PersistableEnumConverter
 * @description: JPA枚举类型转换
 * @author: king
 * @date: 2020-11-16
 **/
@Api(tags = "JPA枚举类型转换", produces = "PersistableEnumConverter")
public interface PersistableEnumConverter<T extends Enum<T> & BaseDbEnum<E>, E> extends AttributeConverter<T, E> {

 @SuppressWarnings("unchecked")
 default Class<T> getEnumClass() {
  return (Class<T>) ClassUtils.getTypeArgumentOfSuperClass(this, PersistableEnumConverter.class, 0);
 }

 @Override
 default E convertToDatabaseColumn(@Nullable final T enumValue) {
  return enumValue == null ? null : enumValue.getDbValue();
 }

 @Override
 default T convertToEntityAttribute(@Nullable final E dbData) {
  return dbData == null
          ? null
          : Stream.of(getEnumClass().getEnumConstants())
          .filter(value -> value.getDbValue().equals(dbData))
          .findFirst()
          .orElse(null);
 }

}
